package com.dubbo.provider.service.impl;

import com.alibaba.dubbo.common.extension.ExtensionLoader;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSONObject;
import com.dubbo.api.service.CostService;
import com.dubbo.provider.service.balance.MyBalance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

/**
 * 花费服务
 */
public class CostServiceImpl implements CostService {

    Logger logger = LoggerFactory.getLogger(CostServiceImpl.class);

    @Value("${dubbo.service.port}")
    private String port;
    /**
     * 假设之前总花费了100
     */
    private final Integer totalCost = 1000;

    /**
     * 之前总和 加上 最近一笔
     * @param cost
     * @return
     */
    @Override
    public Integer add(int cost) {
        logger.info("===========add方法服务端口:{}===========", port);
        return totalCost + cost;
    }

    @Override
    public String update(String param) {
        logger.info("===========update方法服务端口:{}===========", port);
        RpcContext rpcContext = RpcContext.getContext();
        boolean providerSide = rpcContext.isProviderSide();
        boolean consumerSide = rpcContext.isConsumerSide();
        if (providerSide) {
            logger.info("===========服务提供方上下文信息:{}===========", JSONObject.toJSONString(rpcContext));
        } else if (consumerSide){
            logger.info("===========服务消费方上下文信息:{}===========", JSONObject.toJSONString(rpcContext));
        }
        ExtensionLoader<MyBalance> loader = ExtensionLoader.getExtensionLoader(MyBalance.class);
        MyBalance myBalance1 = loader.getExtension("myBalance1");
        try {
            myBalance1.loadBalance();
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }
}
